package com.tanjun.userservice.web.biz.admin;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.tanjun.common.annotation.Edit;
import com.tanjun.common.constants.DefaultConstant;
import com.tanjun.common.enums.user.AdminUserTypeEnum;
import com.tanjun.common.enums.user.UserTypeEnum;
import com.tanjun.common.exception.BizException;
import com.tanjun.common.model.LoginUserInfo;
import com.tanjun.common.response.PageResponse;
import com.tanjun.common.utils.ConvertUntil;
import com.tanjun.userservice.apiservice.request.adminuser.AdminResetPasswordRequest;
import com.tanjun.userservice.apiservice.request.adminuser.AdminUserIdListRequest;
import com.tanjun.userservice.apiservice.request.adminuser.AdminUserPageRequestRequest;
import com.tanjun.userservice.apiservice.request.adminuser.AdminUserRequest;
import com.tanjun.userservice.apiservice.response.admindept.admin.DeptResponse;
import com.tanjun.userservice.apiservice.response.adminuser.admin.AdminUserDetailResponse;
import com.tanjun.userservice.web.service.input.AdminUserInput;
import com.tanjun.userservice.web.service.role.entity.BaseAdminRoleEntity;
import com.tanjun.userservice.web.service.role.BaseAdminRoleService;
import com.tanjun.userservice.web.service.role.BaseAdminUserRoleService;
import com.tanjun.userservice.web.service.user.entity.BaseAdminDeptEntity;
import com.tanjun.userservice.web.service.user.entity.BaseAdminUserEntity;
import com.tanjun.userservice.web.service.user.BaseAdminDeptService;
import com.tanjun.userservice.web.service.user.BaseAdminUserService;
import com.tanjun.web.service.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.tanjun.common.constants.DefaultConstant.DEFAULT_ADMIN_PASSWORD;

@Service
@Slf4j
public class AdminUserBiz  {
    @Autowired
    private BaseAdminUserService baseAdminUserService;
    @Autowired
    private BaseAdminDeptService baseAdminDeptService;
    @Autowired
    private BaseAdminUserRoleService baseAdminUserRoleService;
    @Autowired
    private BaseAdminRoleService baseAdminRoleService;

    /**
     * 新增管理员用户
     *
     * @param paramVo
     */
    public void addAdminUser(AdminUserRequest paramVo) {
        //1.判断用户是否存在
        LoginUserInfo loginUserInfo= LoginUserUtil.getLoginUserInfo();
        if(paramVo.getUserType()== AdminUserTypeEnum.SYSTEM){
            Assert.notNull(paramVo.getDeptId());
            if(loginUserInfo.getUserType()!= UserTypeEnum.ADMIN){
                throw new BizException("当前用户无法添加系统用户");
            }
        }
        if(paramVo.getUserType()==AdminUserTypeEnum.VENDOR) {
            Assert.notNull(paramVo.getVendorId());
        }
        AdminUserInput userBo= ConvertUntil.convert(paramVo, AdminUserInput.class);
        userBo.setOperator(LoginUserUtil.getAdminOperate());
        userBo.setOriPassword(DEFAULT_ADMIN_PASSWORD);
        baseAdminUserService.addOrUpdateUserBase(userBo);
    }

    /**
     * 修改管理员用户
     *
     * @param paramVo
     */
    public void updateAdminUser(@Validated(Edit.class) AdminUserRequest paramVo) {
        log.info("update admin user:{}",paramVo);
        AdminUserInput userBo= ConvertUntil.convert(paramVo, AdminUserInput.class);
        userBo.setOperator(LoginUserUtil.getAdminOperate());

        baseAdminUserService.addOrUpdateUserBase(userBo);
    }

    /**
     * 删除用户
     *
     * @param paramVo 用户id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delAdminUser(AdminUserIdListRequest paramVo) {
        paramVo.getIds().forEach(baseAdminUserService::delAdminUserByUserId);
    }

    public AdminUserDetailResponse getByUsrId(Long userId){
        BaseAdminUserEntity adminUser=baseAdminUserService.getAdminUserByUserId(userId);
        if(adminUser==null){
            return null;
        }
        AdminUserDetailResponse adminUserDetailResponse = ConvertUntil.convert(adminUser, AdminUserDetailResponse.class);
        BaseAdminDeptEntity dept=baseAdminDeptService.getById(adminUserDetailResponse.getDeptId());
        adminUserDetailResponse.setDept(ConvertUntil.convert(dept, DeptResponse.class));

        List<BaseAdminRoleEntity> listRole=baseAdminRoleService.listRolesByIds(adminUserDetailResponse.getRoleIdList());
        adminUserDetailResponse.setRoleNames(listRole.stream().map(BaseAdminRoleEntity::getRoleName)
                .collect(Collectors.joining(DefaultConstant.VIEW_JOIN)));

        adminUserDetailResponse.setRoleIdList(listRole.stream().map(BaseAdminRoleEntity::getRoleId).toList());
        return adminUserDetailResponse;
    }



    /**
     * 分页查询用户信息
     *
     * @param paramVo 查询条件
     * @return 分页的用户信息
     */
    public PageResponse<AdminUserDetailResponse> listPage(AdminUserPageRequestRequest paramVo) {
        List<Long> deptIdList=null;
        if(paramVo.getDeptId()!=null){
            deptIdList=baseAdminDeptService.getChildrenAndSelfDeptId(paramVo.getDeptId());
        }
        Page<BaseAdminUserEntity> page=baseAdminUserService.page(new Page<>(paramVo.getPageNum(), paramVo.getPageSize()),
                QueryChain.of(BaseAdminUserEntity.class)
                        .like(BaseAdminUserEntity::getUserName,paramVo.getUserName(),StrUtil.isNotEmpty(paramVo.getUserName()))
                        .like(BaseAdminUserEntity::getRealName,paramVo.getRealName(),StrUtil.isNotEmpty(paramVo.getRealName()))
                        .eq(BaseAdminUserEntity::getPhone,paramVo.getPhone(),StrUtil.isNotEmpty(paramVo.getPhone()))
                        .eq(BaseAdminUserEntity::getEmail,paramVo.getEmail(),StrUtil.isNotEmpty(paramVo.getEmail()))
                        .eq(BaseAdminUserEntity::getEnabled,paramVo.getEnabled(),paramVo.getEnabled()!=null)
                        .in(BaseAdminUserEntity::getDeptId,deptIdList,paramVo.getDeptId()!=null)
                        .between( BaseAdminUserEntity::getCreateTime,
                                paramVo.getCreateTimeRange()!=null&&paramVo.getCreateTimeRange().length==2?paramVo.getCreateTimeRange()[0]:null,
                                paramVo.getCreateTimeRange()!=null&&paramVo.getCreateTimeRange().length==2?paramVo.getCreateTimeRange()[1]:null,
                                paramVo.getCreateTimeRange()!=null)
                        .orderBy(BaseAdminUserEntity::getUserId).desc()
                );
        PageResponse<AdminUserDetailResponse> pageResponse=ConvertUntil.convertPage(page, AdminUserDetailResponse.class);
        if(CollectionUtil.isNotEmpty(pageResponse.getList())){
            //设置部门信息
            Set<Long> setDept=pageResponse.getList().stream().map(AdminUserDetailResponse::getDeptId).collect(Collectors.toSet());
            List<BaseAdminDeptEntity> listDept= baseAdminDeptService.listAdminDeptById(setDept);
            Map<Long, BaseAdminDeptEntity> mapDept=listDept.stream().collect(Collectors.toMap(BaseAdminDeptEntity::getId, Function.identity()));
            Map<Long,String> mapRoleName=new HashMap<>();
            pageResponse.getList().forEach(d->{
                d.setDept(ConvertUntil.convert(mapDept.get(d.getDeptId()), DeptResponse.class));
                //设置用户的角色
                d.setRoleIdList(baseAdminUserRoleService.getUserRoleIds(d.getUserId()));
                //设置角色名称
                List<String> listRoleNames=new ArrayList<>();
                if(CollectionUtil.isNotEmpty(d.getRoleIdList())){
                    d.getRoleIdList().forEach(roleId->{
                        String roleName=mapRoleName.get(roleId);
                        if(roleName!=null){
                            listRoleNames.add(roleName);
                        }else {
                           BaseAdminRoleEntity role= baseAdminRoleService.getRoleById(roleId);
                           if(role!=null){
                               roleName=role.getRoleName();
                           }
                           mapRoleName.put(roleId,roleName);
                        }
                        listRoleNames.add(roleName);
                    });
                }
                d.setRoleNames(listRoleNames.stream().collect(Collectors.joining(DefaultConstant.VIEW_JOIN)));
            });
        }
        return pageResponse;
    }

    /**
     * 重置密码
     *
     * @param paramVo 重置密码
     */
    public void resetPassword(AdminResetPasswordRequest paramVo) {
        baseAdminUserService.resetPassword(paramVo.getUserId(), paramVo.getPassword());
    }




}
